#!/bin/bash -x

# This is an example of a Java application.
# However since this application is portable and stores its indexes next to it, it is better to use it
# without an AppImage. (FIXME)

set +e

APP=DocFetcher
mkdir -p ./$APP/$APP.AppDir/usr/bin
cd ./$APP

wget -q https://github.com/AppImage/AppImages/raw/master/functions.sh -O ./functions.sh
. ./functions.sh

# Get Java
wget -c --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u66-b17/jre-8u66-linux-x64.tar.gz

# Get DocFetcher 
URL="http://downloads.sourceforge.net/project/docfetcher/docfetcher/1.1.17/docfetcher-1.1.17-portable.zip"
wget -c "$URL"

cd $APP.AppDir

unzip ../docfetcher-*.zip
find . -name *exe -exec rm {} \;
rm -rf DocFetcher-*/DocFetcher.app/

mv DocFetcher-*/* usr/bin
rm -rf DocFetcher-*/

# Install java
tar xf ../jre*
( mkdir -p usr/bin/bin ; cd usr/bin/bin ; ln -s ../../../jre*/bin/java . )

# Write desktop file
cat > docfetcher.desktop <<\EOF
[Desktop Entry]
Name=DocFetcher
Exec=DocFetcher.sh
Icon=docfetcher
Comment=DocFetcher is an Open Source desktop search application: It allows you to search the contents of files on your computer. Can read the following archive formats: zip, 7z, rar, tar.*. Can read Outlook PST files.
EOF

get_apprun

# Add desktop integration
XAPP=DocFetcher.sh
wget -O ./usr/bin/$XAPP.wrapper https://raw.githubusercontent.com/probonopd/AppImageKit/master/desktopintegration
chmod a+x ./usr/bin/$XAPP.wrapper
sed -i -e "s|Exec=$XAPP|Exec=$XAPP.wrapper|g" docfetcher.desktop

# Get version
VERSION=$(grep -r "DocFetcher .*<br" ./usr/bin/help/English/DocFetcher_Manual.html | head -n 1 | xargs | cut -d " " -f 2 | cut -d "<" -f 1)

# Move icon into place
cp usr/bin/img/docfetcher128.png docfetcher.png

# Configure DocFetcher to write to /tmp rather than to the AppImage
( cd usr/bin ; rm -rf indexes ; ln -s /tmp indexes )

# Go out of AppImage
cd ..

generate_appimage
